package com.gitee.candy.utils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;

/**
 * @author suYanLong
 * @date 2022年06月13日 18:00
 */
public class CountDownLatchTask {

    public static void main(String[] args) throws InterruptedException {
        countDownLatch();
        exchange();
    }

    // 线程顺序执行
    private static void joinShunXu() throws InterruptedException {
        System.out.println("start");

        Thread t = new Thread(() -> {
            for (int i = 0; i < 5; i++) {

                System.out.println(i);

                try {

                    Thread.sleep(500);

                } catch

                (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        });

        t.start();

        t.join();

        System.out.println("end");
    }

    // 统计多个线程总的执行时间
    private static void countDownLatch() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            }.start();
        }

        countDownLatch.await();
        System.out.println(countDownLatch.getCount());
        System.out.println(String.format("耗时：%sms", System.currentTimeMillis() - start));
    }

    // 两个线程交换数据
    private static void exchange() {
        Exchanger exchanger = new Exchanger();

        new Thread(() -> {
            try {
                Object data = "-公众号Java技术栈AAA";
                System.out.println(Thread.currentThread().getName() + data);

                // 开始交换数据
                data = exchanger.exchange(data);
                System.out.println(Thread.currentThread().getName() + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                Object data = "-公众号Java技术栈BBB";
                System.out.println(Thread.currentThread().getName() + data);

                // 开始交换数据
                data = exchanger.exchange(data);
                System.out.println(Thread.currentThread().getName() + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}
